# !/usr/bin/python
# -- coding: utf-8 --

__author__ = 'WLH'

from flycmditem import *
from log_entry import *
from temputils import *

from xml.dom import minidom
import codecs
import os
import sys
import time
import stat

strCurTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

# Translate Data type
def DataType(para):
    if para == 'U8':
        return 'byte'
    if para == 'S8':
        return 'sbyte'
    if para == 'U16':
        return 'ushort'
    if para == 'S16':
        return 'short'
    if para == 'U32':
        return 'uint'
    if para == 'S32':
        return 'int'
    if para == 'FP32':
        return 'float'
    if para == 'FP64':
        return 'double'
    else:
        return '?'

# Translate Data Size by data type
def DataSize(para):
    if 'U8' == para or "S8" == para:
        return 1
    if 'U16' == para or "S16" == para:
        return 2
    if 'U32' == para or "S32" == para or "FP32" == para:
        return 4
    if para == 'FP64':
        return 8
    else:
        return 0

curDir = cur_file_dir()
root_dir = os.path.normpath(curDir + '/../')

print ('Root path: ' + root_dir)

if not os.path.exists(root_dir):
    print ('Can not find Directory: ' + os.path.abspath(root_dir))
    exit(1)


# Open Template files
print ("Open Template files...")

print ("Open tmp_telemetry.cs")
tmpFile = os.path.normpath(root_dir + '/CodeGear/template/tmp_telemetry.cs')
txt = codecs.open(tmpFile, 'r', 'utf-8').read()
temp_telemetry_inc = UavTemplate(txt)

print ("Open tmp_telemetry_s.cs")
tmpFile = os.path.normpath(root_dir + '/CodeGear/template/tmp_telemetry_s.cs')
txt = codecs.open(tmpFile, 'r', 'utf-8').read()
temp_tlm_entry = UavTemplate(txt)

print ("Open tmp_flycmdid.cs")
tmpFile = os.path.normpath(root_dir + '/CodeGear/template/tmp_flycmdid.cs')
txt = codecs.open(tmpFile, 'r', 'utf-8').read()
temp_flycmdid = UavTemplate(txt)

# print u"已将XML描述转换成Python中对象"
# 至此已将XML描述转换成Python中对象
# For Debug
# for item in log_entry_list:
#    item.Dump()

print ("Template Proc statuscode")
# -----------------------------------------------------------
# status code Template Proc开始
# -----------------------------------------------------------
statuscodeFile = os.path.normpath(curDir + '/template/tmp_rspcode.cs')
txt = codecs.open(statuscodeFile, 'r', 'utf-8').read()
temp_statuscode_inc = UavTemplate(txt)
# Open XML data type define files
rspcodeFile = os.path.normpath(curDir + '/share/rspcode.xml')
doc_rspcode = minidom.parse(rspcodeFile)

dict_rspcode_inc = dict()
statusItems = doc_rspcode.getElementsByTagName("Code")

dict_rspcode_inc["RSP_CODE_DEFINE"]  = ''
dict_rspcode_inc["RSP_DICT1_DEFINE"] = ''
dict_rspcode_inc["RSP_DICT2_DEFINE"] = ''

for objitem in statusItems:
    name  = objitem.getAttribute("name")
    note  = objitem.getAttribute("note")
    note1 = objitem.getAttribute("note1")
    rspcode = objitem.getAttribute("ID")
    dict_rspcode_inc["RSP_CODE_DEFINE"]  += ('\tRSP_%s ' % name).ljust(35)
    dict_rspcode_inc["RSP_CODE_DEFINE"]  += ('=%s,' % rspcode).ljust(6)
    dict_rspcode_inc["RSP_CODE_DEFINE"]  += '/*%s*/\n' % note
    dict_rspcode_inc["RSP_DICT1_DEFINE"] += '\t\t{%s, \"%s\"},\n' % (rspcode, note1)
    dict_rspcode_inc["RSP_DICT2_DEFINE"] += '\t\t{%s, \"%s\"},\n' % (rspcode, note)

target_file = os.path.normpath(root_dir + '/Link/RspCode.cs')
if os.path.exists(target_file):
    os.chmod(target_file, stat.S_IWRITE)
outfile = codecs.open(target_file, 'w', 'utf-8')
txt = temp_statuscode_inc.safe_substitute(dict_rspcode_inc)
outfile.write(txt)
outfile.close()
os.chmod(target_file, stat.S_IROTH)

# -----------------------------------------------------------
# status code Template Proc结束
# -----------------------------------------------------------

print ("Template Proc telemetry")
# -----------------------------------------------------------
# telemetry Template Proc开始
# -----------------------------------------------------------
xml_tlm_file = os.path.normpath(root_dir + '/CodeGear/share/telemetry.xml')
tlmItems = minidom.parse(xml_tlm_file).getElementsByTagName("TLM")
dict_tlm_inc = dict()
dict_tlm_inc["GEN_TIME"] = strCurTime
dict_tlm_inc["STD_TLM_DEF"] = ''
for i, item in enumerate(tlmItems):
    # 解析成员变量
    memItesms = item.getElementsByTagName("Item")
    tlmName  = item.getAttribute("Name")

    dict_tlm_entry_s = dict()
    dict_tlm_entry_s["MEMBER_INFO"] = '\t'
    dict_tlm_entry_s["TLM_TYPE"] = tlmName
    dict_tlm_entry_s["STR_INFO"] = ''
    for j, memItem in enumerate(memItesms):
        mName  = memItem.getAttribute("name")
        mType  = memItem.getAttribute("type")
        mUnits = memItem.getAttribute("units")
        mNode  = memItem.getAttribute("note")
        dict_tlm_entry_s["MEMBER_INFO"] += 'public %s %s;// %s, %s\n\t' % (DataType(mType).ljust(6), mName.ljust(15), mNode, mUnits)
        dict_tlm_entry_s["STR_INFO"]    += "%s:{%s}{delimiter}"% (mName.ljust(12),mName)
    txt = temp_tlm_entry.safe_substitute(dict_tlm_entry_s)
    dict_tlm_inc["STD_TLM_DEF"] += txt

target_file = os.path.normpath(root_dir + '/Link/Telemetry.cs')
if os.path.exists(target_file):
    os.chmod(target_file, stat.S_IWRITE)
outfile = codecs.open(target_file, 'w', 'utf-8')
txt = temp_telemetry_inc.safe_substitute(dict_tlm_inc)
outfile.write(txt)
outfile.close()
os.chmod(target_file, stat.S_IROTH)
# -----------------------------------------------------------
# StdTlm Template Proc结束
# -----------------------------------------------------------

# -----------------------------------------------------------
# log_entry Template Proc结束
# -----------------------------------------------------------

print ("Template Proc flycmd")
# -----------------------------------------------------------
# flycmd Template Proc开始
# -----------------------------------------------------------
# Open XML data type define files
print ("Open flycmd.xml")
flycmdList = []
tmp_path = os.path.normpath(root_dir + '/CodeGear/share/flycmd.xml')
doc_flycmd = minidom.parse(tmp_path)
flycmds = minidom.parse(tmp_path).getElementsByTagName("FlyCmd")
for i, item in enumerate(flycmds):
    flycmd = FlycmdItem()
    flycmd.Name = item.getAttribute("name")
    flycmd.Id = item.getAttribute("id")
    flycmdList.append(flycmd)
# For Debug
#for item in flycmdList:
#    item.Dump()

dict_flycmd_src = dict()
dict_flycmd_src["GEN_TIME"] = strCurTime
dict_flycmd_src["FLY_CMD_ID"] = ''
for i, flycmd in enumerate(flycmdList):
    dict_flycmd_src["FLY_CMD_ID"] += "\t\tCMD_%s=%s,\n" % (flycmd.Name.upper().ljust(12), flycmd.Id)

dict_flycmd_src["FLY_CMD_ID"] += "\t\tCMD_NULL = 0"

target_file = os.path.normpath(root_dir + '/Mission/FlyCmdId.cs')
if os.path.exists(target_file):
    os.chmod(target_file, stat.S_IWRITE)
outfile = codecs.open(target_file, 'w', 'utf-8')
txt = temp_flycmdid.safe_substitute(dict_flycmd_src)
outfile.write(txt)
outfile.close()
os.chmod(target_file, stat.S_IROTH)

# -----------------------------------------------------------
# flycmd Template Proc结束
# -----------------------------------------------------------

print ('----------------------------END----------------------------')
